package com.win.all.service.impl;

import com.win.all.service.ILoadBanlanceService;

import java.util.HashMap;
import java.util.Random;

public class LoadBanlanceServiceImpl implements ILoadBanlanceService {

    HashMap<Integer, Integer> weightsMapCache = null;
    int totalWeight = 0;

    /**
     * 初始化权重设置数据
     *
     * @param weights 权重设置
     */
    @Override
    public void setWeights(int[] weights) {
        int placeholder = 0;
        weightsMapCache = new HashMap<>();
        for (int i = 0; i < weights.length; i++) {
            for (int j = 0; j < weights[i]; j++) {
                //按照权重来占位，一个数字1占一个位，key代表占的位，value代表服务器下标
                weightsMapCache.put(placeholder, i);
                placeholder++;
            }
        }
        totalWeight = placeholder;
    }

    /**
     * 获取选中节点的下标
     */
    @Override
    public int getNextWeightsObject() {
        Random random = new Random();
        //随机数落到哪个位，对应的value就是节点下标，因为权重大的占的位多，所以随机数落到的概率也相应大
        int key = random.nextInt(totalWeight);
        return weightsMapCache.get(key);
    }
}
